<template>
  <div id="homePage">
    <!-- 搜索区域 - 简约设计 -->
    <div class="search-section">
      <div class="search-container">
        <h1 class="search-title">发现精彩图片</h1>
        <p class="search-subtitle">从海量图片中找到你需要的</p>
        <div class="search-bar">
          <a-input-search
            v-model:value="searchParams.searchText"
            placeholder="搜索图片..."
            enter-button="搜索"
            size="large"
            @search="doSearch"
            class="search-input"
          />
        </div>
      </div>
    </div>

    <!-- 筛选区域 - 简约设计 -->
    <div class="filter-section">
      
      <div class="tag-filter" v-if="tagList.length > 0">
        <a-space :size="[8, 8]" wrap>
          <a-checkable-tag
            v-for="(tag, index) in tagList"
            :key="tag"
            v-model:checked="selectedTagList[index]"
            @change="() => handleTagClick(tag)"
            class="tag-item"
          >
            {{ tag }}
          </a-checkable-tag>
        </a-space>
    </div>
  </div>



  <!-- 图片列表 -->
  <div class="picture-section">
    <PictureList :dataList="dataList" :loading="loading" />
  </div>

    <!-- 加载更多 -->
    <div class="load-more-section" v-if="dataList.length > 0 && dataList.length < total">
        <span
          v-if="!loadingMore"
          @click="loadMore"
          :class="['load-more-text', { 'disabled': dataList.length >= total }]"
        >
          加载更多
        </span>
        <span v-else class="load-more-text loading-text">
          加载中...
        </span>
      </div>
    <div class="no-more-data" v-else-if="dataList.length > 0 && dataList.length >= total">
      <p>已显示全部图片</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import {
  listPictureTagCategoryUsingGet,
  listPictureVoByPageUsingPost,
  uploadPictureBySearchHomePageUsingPost,
} from '@/api/pictureController.ts'
import { message } from 'ant-design-vue'
import PictureList from '@/components/PictureList.vue' // 定义数据

// 定义数据
const dataList = ref<API.PictureVO[]>([])
const total = ref(0)
const loading = ref(true)
const loadingMore = ref(false)

// 搜索条件
const searchParams = reactive<API.PictureQueryRequest>({
  current: 1,
  pageSize: 12,
  sortField: 'createTime',
  sortOrder: 'descend',
})

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    // 转换搜索参数
    const params = {
      ...searchParams,
      tags: [] as string[],
    }
    // [true, false, false] => ['java']
    selectedTagList.value.forEach((useTag, index) => {
      if (useTag) {
        params.tags.push(tagList.value[index])
      }
    })
    const res = await listPictureVoByPageUsingPost(params)
    if (res.data.code === 0 && res.data.data) {
      dataList.value = res.data.data.records ?? []
      total.value = Number(res.data.data.total ?? 0)
    } else {
      message.error('获取数据失败，' + res.data.message)
    }
  } catch (error) {
    console.error('Error fetching data:', error)
    message.error('获取数据失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

// 加载更多数据
const loadMore = async () => {
  if (loadingMore.value || dataList.value.length >= total.value) return
  
  loadingMore.value = true
  searchParams.current++
  
  try {
    // 转换搜索参数
    const params = {
      ...searchParams,
      tags: [] as string[],
    }
    // [true, false, false] => ['java']
    selectedTagList.value.forEach((useTag, index) => {
      if (useTag) {
        params.tags.push(tagList.value[index])
      }
    })
    const res = await listPictureVoByPageUsingPost(params)
    if (res.data.code === 0 && res.data.data) {
      // 追加新数据而不是替换
      dataList.value = [...dataList.value, ...(res.data.data.records ?? [])]
    } else {
      message.error('加载更多失败，' + res.data.message)
      // 恢复页码
      searchParams.current--
    }
  } catch (error) {
    console.error('Error loading more data:', error)
    message.error('加载更多失败，请检查网络连接')
    // 恢复页码
    searchParams.current--
  } finally {
    loadingMore.value = false
  }
}

// 处理标签点击事件
const handleTagClick = (tag: string) => {
  // 重置所有标签选中状态
  selectedTagList.value = selectedTagList.value.map(() => false)
  // 找到当前点击的标签索引并设置为选中
  const tagIndex = tagList.value.indexOf(tag)
  if (tagIndex !== -1) {
    selectedTagList.value[tagIndex] = true
  }
  // 将标签文字填充到搜索框
  searchParams.searchText = tag
  // 执行搜索
  doSearch()
}

// 搜索
const doSearch = async () => {
  // 重置搜索条件
  searchParams.current = 1
  loading.value = true
  try {
    // 准备搜索请求参数 - 直接使用搜索框中的值，避免使用可能有缓存的逻辑
    const uploadParams: API.PictureUploadByBatchRequest = {
      // 直接使用搜索框中的文字作为搜索关键词
      searchText: searchParams.searchText || '',
      count: 10 // 设置默认抓取数量
    }
    
    // 调用新的搜索接口
    const res = await uploadPictureBySearchHomePageUsingPost(uploadParams)
    if (res.data.code === 0 && res.data.data) {
      // 搜索时替换数据而不是追加
      dataList.value = res.data.data.records ?? []
      total.value = Number(res.data.data.total ?? 0)
      message.success(`找到 ${dataList.value.length} 张相关图片`)
    } else {
      message.error('搜索失败，' + res.data.message)
    }
  } catch (error) {
    console.error('Error searching pictures:', error)
    message.error('搜索失败，请检查网络连接或权限')
  } finally {
    loading.value = false
  }
}

// 获取选中的标签文字，如果没有选中的标签则使用搜索框中的文字
const getSelectedTagsText = (): string => {
  const selectedTags = tagList.value.filter((_, index) => selectedTagList.value[index])
  if (selectedTags.length > 0) {
    // 返回第一个选中的标签文字
    return selectedTags[0]
  }
  // 如果没有选中的标签，返回搜索框中的文字
  return searchParams.searchText || ''
}

// 标签列表
const tagList = ref<string[]>([])
const selectedTagList = ref<boolean[]>([])

/**
 * 获取标签和分类选项
 * @param values
 */
const getTagCategoryOptions = async () => {
  try {
    const res = await listPictureTagCategoryUsingGet()
    if (res.data.code === 0 && res.data.data) {
      tagList.value = res.data.data.tagList ?? []
      // 初始化标签选中状态
      selectedTagList.value = new Array(tagList.value.length).fill(false)
    } else {
      message.error('获取标签分类列表失败，' + res.data.message)
    }
  } catch (error) {
    console.error('Error fetching tag categories:', error)
    message.error('获取标签分类失败，请检查网络连接')
  }
}

// 页面加载时获取数据，请求一次
onMounted(async () => {
  await getTagCategoryOptions()
  fetchData()
})

const router = useRouter()
</script>

<style scoped>
#homePage {
  min-height: 100vh;
  background: linear-gradient(135deg, #ffffff 0%, #fafafa 100%);
}

/* 搜索区域 - 简约设计 */
.search-section {
  padding: 80px 0 60px;
  text-align: center;
  background: #ffffff;
}

.search-container {
  max-width: 600px;
  margin: 0 auto;
  padding: 0 20px;
}

.search-title {
  font-size: 48px;
  font-weight: 300;
  color: #000000;
  margin: 0 0 16px;
  letter-spacing: -1px;
}

.search-subtitle {
  font-size: 18px;
  color: #666666;
  margin: 0 0 40px;
  font-weight: 400;
}

.search-bar {
  max-width: 600px;
  margin: 0 auto;
}

.search-input {
  border-radius: 8px;
  border: 2px solid #f0f0f0;
  transition: all 0.3s ease;
}

.search-input:hover {
  border-color: #d0d0d0;
}

.search-input:focus-within {
  border-color: #000000;
  box-shadow: 0 0 0 4px rgba(0, 0, 0, 0.1);
}

/* 筛选区域 - 简约设计 */
.filter-section {
  padding: 20px;
  background: #fafafa;
  border-top: 1px solid #f0f0f0;
  border-bottom: 1px solid #f0f0f0;
  position: sticky;
  top: 0;
  z-index: 100;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.category-filter {
  margin-bottom: 24px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.tag-filter {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
  gap: 16px;
}

.filter-label {
  font-size: 14px;
  font-weight: 600;
  color: #333333;
  min-width: 60px;
  display: inline-flex;
  align-items: center;
  height: 32px; /* 与标签项高度保持一致 */
  vertical-align: middle;
}

.filter-btn {
  border-radius: 20px;
  border: 1px solid #e0e0e0;
  background: #ffffff;
  color: #666666;
  font-weight: 500;
  transition: all 0.2s ease;
}

.filter-btn:hover {
  border-color: #000000;
  color: #000000;
}

.filter-btn.ant-btn-primary {
  border-color: #000000;
}

.tag-item {
  border-radius: 0;
  padding: 8px 16px 6px;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.2s ease;
  background: transparent;
  border: none;
  color: #666666;
  position: relative;
}

/* 标签悬停效果 */
.tag-item:hover {
  color: #000000;
  background: rgba(0, 0, 0, 0.03);
}

/* 标签下划线效果 */
.tag-item::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 0;
  height: 2px;
  background: #000000;
  transition: width 0.3s ease;
}

/* 选中标签显示下划线 */
.tag-item.ant-tag-checkable-checked::after {
  width: 40px;
}

/* 确保未选中标签不显示下划线 */
.tag-item:not(.ant-tag-checkable-checked)::after {
  width: 0;
}

/* 选中标签样式 */
.tag-item.ant-tag-checkable-checked {
  color: #000000;
  background: transparent;
}

/* 图片列表区域 */
.picture-section {
  padding: 40px 20px;
  background: #ffffff;
}

/* 加载更多按钮区域 */
.load-more-section {
  padding: 40px 20px 80px;
  background: #ffffff;
  text-align: center;
}

.load-more-text {
        display: inline-block;
        font-size: 18px;
        font-weight: 500;
        color: #666666;
        cursor: pointer;
        padding: 20px;
        margin: 0 auto;
        transition: all 0.3s ease;
        text-decoration: underline;
      }
      
      .load-more-text:hover:not(.disabled) {
        color: #000000;
        transform: scale(1.05);
      }
      
      .load-more-text.disabled {
        color: #d9d9d9;
        cursor: not-allowed;
        text-decoration: none;
      }
      
      .load-more-text.loading-text {
        color: #999999;
        cursor: wait;
        text-decoration: none;
      }

.no-more-data {
  padding: 40px 20px 80px;
  background: #ffffff;
  text-align: center;
  color: #999999;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-title {
    font-size: 36px;
  }
  
  .search-subtitle {
    font-size: 16px;
  }
  
  .search-section {
    padding: 60px 0 40px;
  }
  
  .filter-section {
    padding: 30px 20px;
  }
  
  .category-filter,
  .tag-filter {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>
